package com.ruoyi.web.controller.workflow;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.workflow.domain.BpmnInfo;
import com.ruoyi.workflow.service.IBpmnInfoService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 流程定义Controller
 * 
 * @author xiaodu
 * @date 2023-06-17
 */
@RestController
@RequestMapping("/workflow/bpmnInfo")
public class BpmnInfoController extends BaseController
{
    @Autowired
    private IBpmnInfoService bpmnInfoService;

    /**
     * 查询流程定义列表
     */
    @PreAuthorize("@ss.hasPermi('workflow:bpmnInfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(BpmnInfo bpmnInfo)
    {
        startPage();
        List<BpmnInfo> list = bpmnInfoService.selectBpmnInfoList(bpmnInfo);
        return getDataTable(list);
    }


    /**
     * 部署流程文件
     */
    @PreAuthorize("@ss.hasPermi('workflow:bpmnInfo:deploy')")
    @Log(title = "流程定义", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult deploy(MultipartFile[] fileList, BpmnInfo bpmnInfo) throws IOException {
        //部署流程文件
        bpmnInfoService.deploy(fileList,bpmnInfo);
        return AjaxResult.success("流程部署成功");
    }


    /**
     * 删除流程定义
     */
    @PreAuthorize("@ss.hasPermi('workflow:bpmnInfo:remove')")
    @Log(title = "流程定义", businessType = BusinessType.DELETE)
	@DeleteMapping("{bpmnInfoId}/{deploymentId}")
    public AjaxResult remove(@PathVariable Long bpmnInfoId,@PathVariable String deploymentId)
    {
        Boolean result = bpmnInfoService.deleteBpmnInfoById(bpmnInfoId,deploymentId);
        if(result){
            return AjaxResult.success("删除成功");
        }else{
            return AjaxResult.error("删除失败");
        }
    }

    /**
     * 查看流程文件/流程图
     */
    @PreAuthorize("@ss.hasPermi('workflow:bpmnInfo:readResource')")
    @GetMapping("readResource/{deploymentId}/{fileType}")
    public void readResource(@PathVariable String deploymentId,@PathVariable String fileType, HttpServletResponse resp) throws IOException {
        //1.获取流程文件/流程图输入流
        InputStream in = bpmnInfoService.readResourceFile(deploymentId,fileType);
        //2.把输入流输出到输出流中
        IOUtils.copy(in,resp.getOutputStream());
    }


}
